import React, {PureComponent, useState, useCallback} from 'react';
import {
  StyleSheet,
  View,
  Image,
  DeviceEventEmitter,
  Text,
  ScrollView,
  KeyboardAvoidingView,
  Dimensions,
  Keyboard,
  TouchableOpacity,
} from 'react-native';
import {SwipeListView} from 'react-native-swipe-list-view';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {ImageTitleButton, ImageButton} from '../../../components/Button';
import I18n from 'react-native-i18n';
import {
  setCurrentRoomSpeaker,
  setCurrentRoomListener,
  setCurrentRoom,
  setRoomWidgetLayout,
  updateUserInfo,
  setCurrentRoomRaisedUsers,
} from '../../../redux/action';
import {changeMemberStatus} from '../../../api/channel';
import {BASE_API} from '../../../config';
import {
  LinearButton,
  TextButton,
  LinearBoardButton,
} from '../../../components/Button';
import {LinerBoardTextInput} from '../../../components/TextInput';
import {random} from 'lodash';
import {FlatList} from 'react-native-gesture-handler';
import {Colors} from '../../../styles/common';
const {width, height} = Dimensions.get('window');

const styles = StyleSheet.create({
  loading: {
    position: 'absolute',
    backgroundColor: 'rgba(255,255,255,0.8)',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    // borderTopRightRadius: 30,
    // borderTopLeftRadius: 30,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

class RommWidget extends PureComponent {
  static propTypes = {
    loadingText: PropTypes.string,
    back: PropTypes.func.isRequired,
    pressUserIcon: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      showAdvance: false, //展示陈列品视图
      voiceState: true,
      showHandList: false, //展示举手列表视频
      showChatView: false, //展示聊天视图
      keyboardHeight: 0,
    };

    this.setScrollView = (el) => {
      this.ScrollView = el;
    };
  }

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      this._keyboardDidShow,
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      this._keyboardDidHide,
    );
  }

  _keyboardDidShow = (e) => {
    // 获取键盘高度
    this.setState({
      keyboardHeight: e.endCoordinates.height - 20,
    });
    //   () => {
    //     setTimeout(() => {
    //       console.log('--------');
    //       this.ScrollView.scrollTo({
    //         X: 0,
    //         Y: e.endCoordinates.height,
    //         animated: true,
    //       });
    //     }, 1000);
    //   },
    // );
  };

  _keyboardDidHide = (e) => {
    this.setState({
      keyboardHeight: 0,
    });
    // this.ScrollView.scrollTo({X: 0, Y: 0, animated: true});
  };

  componentWillUnmount() {
    // 移除监听
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();

    if (this.enterRoomEmitter) {
      this.enterRoomEmitter.remove();
    }
  }

  tapShowHandListView = () => {
    this.props.setRoomWidgetLayout({
      height: this.state.showHandList ? 100 : 360,
    });
    this.setState({
      showHandList: !this.state.showHandList,
      showAdvance: false,
      showChatView: false,
    });
  };

  tapShowChatView = () => {
    //回到聊天室
    this.props.pressUserIcon();

    this.props.setRoomWidgetLayout({
      height: this.state.showChatView ? 100 : height + 10,
    });

    this.setState({
      showChatView: !this.state.showChatView,
      showHandList: false,
      showAdvance: false,
    });
  };

  tapCloseChatViewBtn = () => {
    this.props.setRoomWidgetLayout({
      height: 100,
      bottom: 0,
    });

    this.setState({
      showChatView: false,
    });
  };

  //举手或者放弃举手
  raiseHand = () => {
    DeviceEventEmitter.emit('channelMessage', {
      type: 'raisedHand',
      data: {
        status: this.props.userInfo.raisedHand ? false : true,
      },
    });

    this.props.updateUserInfo({
      ...this.props.userInfo,
      raisedHand: this.props.userInfo.raisedHand ? false : true,
    });
  };

  changeMemberListener = () => {
    console.log('下麦成功，成为听众');

    DeviceEventEmitter.emit('channelMessage', {
      type: 'changeMemberListener',
      data: {},
    });

    this.props.updateUserInfo({
      ...this.props.userInfo,
      isSpeaker: 0,
      micphoneState: 0,
    });

    DeviceEventEmitter.emit('micphoneChange', false);
  };

  _voiceChange = () => {
    //改变状态
    this.setState(
      {
        voiceState: !this.state.voiceState,
      },
      () => {
        console.log('改变声音状态' + !this.state.voiceState);
        DeviceEventEmitter.emit('voiceChange', !this.state.voiceState);
      },
    );
  };

  _becomeSpeaker = async () => {
    //上麦
    DeviceEventEmitter.emit('channelMessage', {
      type: 'agreeRaisedHand',
      data: {
        identify: this.props.userInfo.identify,
      },
    });
  };

  _micphoneChange = async () => {
    await this.props.updateUserInfo({
      ...this.props.userInfo,
      micphoneState: !this.props.userInfo.micphoneState,
    });

    DeviceEventEmitter.emit(
      'micphoneChange',
      this.props.userInfo.micphoneState,
    );
  };

  agreeHand = async (item) => {
    console.log('同意举手');
    DeviceEventEmitter.emit('channelMessage', {
      type: 'agreeRaisedHand',
      data: {
        identify: item.id,
      },
    });

    this.props.setCurrentRoomRaisedUsers(
      this.props.raisedHandUsers.filter((eItem) => eItem.id != item.id),
    );
  };

  sendMessage = (item) => {
    console.log('发送文本');

    let a = random(0, 10, false);

    let timestamp = new Date().valueOf();

    DeviceEventEmitter.emit('channelMessage', {
      type: 'chat',
      data: {
        content: this.state.message,
        msgId: this.props.userInfo.userId + '-' + timestamp,
      },
    });

    this.setState(
      {
        message: '',
      },
      () => {
        Keyboard.dismiss();
      },
    );
  };

  _renderEmptyChatView = () => (
    <View
      style={{
        height: 300,
        width: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
      }}>
      <Text
        style={{
          color: 'white',
          padding: 10,
          alignSelf: 'center',
          fontSize: 18,
          fontWeight: 'bold',
        }}>
        {'Be the first to chat!'}
      </Text>
      <Text
        style={{
          color: Colors.fontGrayColor_a,
          alignSelf: 'center',
          fontSize: 14,
        }}>
        {'All messages will appear here.'}
      </Text>
    </View>
  );

  _renderEmptyView = () => (
    <View
      style={{
        height: 200,
        flexDirection: 'column',
        justifyContent: 'center',
      }}>
      <Text
        style={{
          color: 'white',
          padding: 20,
          alignSelf: 'center',
          fontSize: 18,
          fontWeight: 'bold',
        }}>
        {'Nobody raised their hands!'}
      </Text>
    </View>
  );

  _renderItem = (item) => {
    return (
      <View
        style={{
          width: '100%',
          height: 70,
          paddingLeft: 20,
          paddingRight: 20,
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}>
          <ImageButton
            btnStyle={{
              width: 50,
              height: 50,
            }}
            imageStyle={{width: 50, height: 50, borderRadius: 30}}
            // onPress={this.props.pressUserIcon}
            source={{
              uri: item.item.avatar,
            }}></ImageButton>
          <Text style={{color: 'white', marginLeft: 20, fontSize: 16}}>
            {item.item.name}
          </Text>
        </View>
        <LinearButton
          buttonStyle={{
            width: 100,
            height: 30,
          }}
          textStyle={{
            fontSize: 16,
          }}
          onPress={() => {
            this.agreeHand(item.item);
          }}
          text={'Agree'}></LinearButton>
      </View>
    );
  };

  render() {
    let chatHeight = height - 300;
    return (
      <View
        style={{
          position: 'absolute',
          bottom: 0,
          left: 0,
          width: '100%',
          paddingTop: 10,
          paddingLeft: 20,
          paddingRight: 20,
          paddingBottom: 30,
          borderTopRightRadius: 30,
          borderTopLeftRadius: 30,
          backgroundColor: 'rgba(53,0,124,0.7)',
        }}>
        {this.state.showHandList ? (
          <View>
            <Text style={{fontSize: 18, color: 'white', fontWeight: 'bold'}}>
              Raised Hands
            </Text>
            <SwipeListView
              useFlatList
              style={{
                width: '100%',
                height: 200,
                marginTop: 20,
                marginBottom: 20,
                borderRadius: 20,
              }}
              ListEmptyComponent={this._renderEmptyView}
              data={this.props.raisedHandUsers}
              keyExtractor={(item, index) => 'room' + index} // 给定的item生成一个不重复的key
              renderItem={this._renderItem}></SwipeListView>
          </View>
        ) : null}
        {this.state.showChatView ? (
          <View style={{width: '100%'}}>
            <View>
              <TouchableOpacity
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  height: 40,
                  paddingLeft: 10,
                  paddingRight: 10,
                  borderRadius: 20,
                  backgroundColor: '#C917ED',
                  alignSelf: 'flex-start',
                }}
                onPress={this.tapCloseChatViewBtn}>
                <Image
                  style={{width: 20, height: 20, marginRight: 10}}
                  source={require('../../../assets/common/arrow_down.png')}
                />
                <Text
                  style={{
                    fontSize: 18,
                    color: 'white',
                    fontWeight: 'bold',
                  }}>
                  {this.props.currentRoom.name}
                </Text>
              </TouchableOpacity>
              <Text
                style={{
                  fontSize: 14,
                  color: Colors.fontGrayColor_a,
                  // height: 30,
                  lineHeight: 30,
                }}>
                {this.props.currentRoom.notice}
              </Text>
            </View>
            <ScrollView
              style={{
                height: chatHeight + 50 + 40,
              }}
              scrollEnabled={false}
              keyboardShouldPersistTaps={'handled'}
              onContentSizeChange={() =>
                this.ScrollView.scrollToEnd({animated: true})
              }
              ref={this.setScrollView}>
              <FlatList
                style={{
                  width: '100%',
                  height: chatHeight + 10,
                  marginBottom: 20,
                }}
                ref={(item) => {
                  this.ListView = item;
                }}
                onContentSizeChange={() =>
                  this.ListView.scrollToEnd({animated: true})
                }
                ListEmptyComponent={this._renderEmptyChatView}
                data={this.props.chatDatas}
                keyExtractor={(item, index) => 'chat' + index} // 给定的item生成一个不重复的key
                renderItem={(item) => {
                  return <ChatItem item={item.item}></ChatItem>;
                }}></FlatList>
              <View
                style={{
                  flexDirection: 'row',
                  width: '100%',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: 50,
                  paddingBottom: 10,
                  paddingTop: 20,
                }}>
                <LinerBoardTextInput
                  style={{
                    flex: 1,
                    height: 40,
                  }}
                  onChangeText={(text) => {
                    this.setState({
                      message: text,
                    });
                  }}
                  defaultValue={this.state.message}
                  placeholder="Input your message"></LinerBoardTextInput>
                <LinearButton
                  buttonStyle={{
                    width: 80,
                    height: 40,
                    marginLeft: 10,
                    marginTop: -8,
                  }}
                  textStyle={{
                    fontSize: 16,
                  }}
                  onPress={() => {
                    this.sendMessage();
                  }}
                  text={'Send'}></LinearButton>
              </View>
              <View
                style={{
                  width: '100%',
                  height: this.state.keyboardHeight,
                }}></View>
            </ScrollView>
          </View>
        ) : (
          <View>
            {this.state.showAdvance ? (
              <View>
                <Image
                  style={{
                    width: '100%',
                    height: 200,
                    marginBottom: 20,
                    borderRadius: 20,
                  }}
                  source={{
                    uri: BASE_API + this.props.currentRoom.images,
                  }}
                />
                <ScrollView style={{height: 150}} bounces={false}>
                  <Text
                    style={{marginBottom: 20, color: 'white', fontSize: 14}}>
                    {this.props.currentRoom
                      ? this.props.currentRoom.introduction
                      : ''}
                  </Text>
                </ScrollView>
              </View>
            ) : null}
            <View
              style={{
                flexDirection: 'row',
              }}>
              {/* <ImageButton
            btnStyle={{
              width: 50,
              height: 50,
            }}
            imageStyle={{
              width: 50,
              height: 50,
              borderRadius: 30,
              backgroundColor: 'green',
            }}
            onPress={this.props.pressUserIcon}
            source={{
              uri: this.props.userInfo.image,
            }}></ImageButton> */}
              <ImageTitleButton
                btnStyle={{
                  width: 40,
                  height: 40,
                  borderRadius: 20,
                  backgroundColor: this.state.showChatView
                    ? '#BD8FFF'
                    : '#C917ED',
                }}
                imageStyle={{width: 15, height: 15}}
                title={'Chat'}
                titleStyle={{fontSize: 12}}
                source={require('../../../assets/room/room_chat.png')}
                onPress={this.tapShowChatView}
              />
              <View
                style={{
                  flex: 1,
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'flex-end',
                  paddingLeft: 10,
                }}>
                {this.props.currentRoom &&
                this.props.currentRoom.introduction.length != 0 ? (
                  <ImageTitleButton
                    btnStyle={{
                      width: 40,
                      height: 40,
                      backgroundColor: this.state.showAdvance
                        ? '#C917ED'
                        : '#BD8FFF',
                      borderRadius: 50,
                      marginLeft: 10,
                    }}
                    imageStyle={{width: 15, height: 15}}
                    title={'auction'}
                    source={require('../../../assets/common/feature.png')}
                    onPress={() => {
                      this.props.setRoomWidgetLayout({
                        height: this.state.showAdvance ? 100 : 480,
                      });
                      this.setState({
                        showAdvance: !this.state.showAdvance,
                      });
                    }}
                  />
                ) : null}
                {this.props.userInfo.isRoomOwner ? (
                  <View style={{position: 'relative'}}>
                    <ImageTitleButton
                      btnStyle={{
                        width: 40,
                        height: 40,
                        backgroundColor: this.state.showHandList
                          ? '#BD8FFF'
                          : '#C917ED',
                        borderRadius: 20,
                      }}
                      imageStyle={{width: 22, height: 22}}
                      title={'Raised Hands'}
                      titleStyle={{fontSize: 12}}
                      source={require('../../../assets/room/hand_list.png')}
                      onPress={this.tapShowHandListView}
                    />
                    {this.props.raisedHandUsers.length != 0 ? (
                      <View
                        style={{
                          position: 'absolute',
                          backgroundColor: 'red',
                          width: 10,
                          height: 10,
                          right: 15,
                          top: -5,
                          borderRadius: 5,
                        }}></View>
                    ) : null}
                  </View>
                ) : !this.props.userInfo.isSpeaker ? (
                  <ImageTitleButton
                    btnStyle={{
                      width: 40,
                      height: 40,
                      backgroundColor: this.props.userInfo.raisedHand
                        ? '#BD8FFF'
                        : '#C917ED',
                      borderRadius: 20,
                    }}
                    imageStyle={{width: 15, height: 15}}
                    title={'Raise Hand'}
                    titleStyle={{fontSize: 12}}
                    source={require('../../../assets/room/raise_hand.png')}
                    onPress={this.raiseHand}
                  />
                ) : null}
                {this.props.userInfo.isSpeaker &&
                this.props.currentRoom &&
                !this.props.currentRoom.isCommonRoom ? (
                  <ImageTitleButton
                    btnStyle={{
                      width: 40,
                      height: 40,
                      backgroundColor: '#C917ED',
                      borderRadius: 20,
                    }}
                    imageStyle={{width: 15, height: 15}}
                    title={'Audience'}
                    titleStyle={{fontSize: 12}}
                    source={require('../../../assets/common/ting.png')}
                    onPress={this.changeMemberListener}
                  />
                ) : null}
                {this.props.userInfo.isRoomOwner &&
                !this.props.userInfo.isSpeaker ? (
                  <ImageTitleButton
                    btnStyle={{
                      width: 40,
                      height: 40,
                      backgroundColor: '#C917ED',
                      borderRadius: 20,
                    }}
                    imageStyle={{width: 10, height: 18}}
                    title={'Speaker'}
                    titleStyle={{fontSize: 12}}
                    source={require('../../../assets/common/microphone.png')}
                    onPress={this._becomeSpeaker}
                  />
                ) : null}
                <ImageTitleButton
                  btnStyle={{
                    width: 40,
                    height: 40,
                    backgroundColor: this.state.voiceState
                      ? '#C917ED'
                      : '#BD8FFF',
                    borderRadius: 20,
                  }}
                  imageStyle={{width: 15, height: 15}}
                  title={'Voice'}
                  titleStyle={{fontSize: 12}}
                  source={require('../../../assets/common/speaker.png')}
                  onPress={this._voiceChange}
                />
                {this.props.userInfo.isSpeaker ? (
                  <ImageTitleButton
                    btnStyle={{
                      width: 40,
                      height: 40,
                      backgroundColor: this.props.userInfo.micphoneState
                        ? '#C917ED'
                        : '#BD8FFF',
                      borderRadius: 20,
                    }}
                    imageStyle={{width: 10, height: 18}}
                    title={'Microphone'}
                    titleStyle={{fontSize: 12}}
                    source={require('../../../assets/common/microphone.png')}
                    onPress={this._micphoneChange}
                  />
                ) : null}
                {/* <ImageButton
              btnStyle={{
                width: 40,
                height: 40,
                backgroundColor: '#BD8FFF',
                borderRadius: 50,
                marginLeft: 10,
              }}
              imageStyle={{width: 15, height: 15}}
              source={require('../../../assets/common/quit.png')}
              onPress={this.props.back}
            /> */}
              </View>
              {this.props.loadingText.length != 0 ? (
                <View style={styles.loading}>
                  <Text>{this.props.loadingText}</Text>
                </View>
              ) : null}
            </View>
          </View>
        )}
      </View>
    );
  }
}

class ChatItem extends PureComponent {
  static propTypes = {
    item: PropTypes.any.isRequired,
  };

  constructor(props) {
    super(props);

    console.log(props);
    let originMsgMaxWidth = width - 40 - 50 - 10;

    this.state = {
      msgMaxWidth: originMsgMaxWidth,
    };
  }

  render() {
    return (
      <View style={{width: '100%'}}>
        <View
          style={{
            maxWidth: '100%',
            flexDirection: 'row',
            alignSelf: 'flex-start',
            alignItems: 'flex-start',
            justifyContent: 'space-between',
            minHeight: 50,
            borderRadius: 25,
            backgroundColor: 'white',
            marginBottom: 15,
            paddingRight: 10,
          }}>
          <ImageButton
            btnStyle={{
              width: 42,
              height: 42,
              margin: 4,
            }}
            imageStyle={{width: 42, height: 42, borderRadius: 21}}
            // onPress={this.props.onPressUser}
            source={{
              uri: this.props.item.avatar,
            }}></ImageButton>
          <Text
            style={{
              color: Colors.fontBlackColor_31,
              fontSize: 16,
              maxWidth: 200,
              height: 50,
              lineHeight: 50,
              fontWeight: 'bold',
            }}
            onLayout={(event) => {
              //约束聊天内容宽度
              let originMsgMaxWidth = width - 40 - 50 - 10;
              if (this.state.msgMaxWidth == originMsgMaxWidth) {
                // console.log(
                //   '约束后，获取名字宽度为' + event.nativeEvent.layout.width,
                // );
                this.setState({
                  msgMaxWidth:
                    originMsgMaxWidth - event.nativeEvent.layout.width,
                });
              }
            }}>
            {this.props.item.name + ': '}
          </Text>
          <Text
            numberOfLines={0}
            style={{
              lineHeight: 20,
              color: Colors.fontPurpleColorLight,
              fontSize: 16,
              marginTop: 15,
              fontWeight: '600',
              marginBottom: 15,
              maxWidth: this.state.msgMaxWidth,
            }}>
            {this.props.item.content}
          </Text>
        </View>
      </View>
    );
  }
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  currentRoom: state.User.currentRoom,
  speakers: state.User.speakers,
  listeners: state.User.listeners,
  raisedHandUsers: state.User.raisedHandUsers,
  chatDatas: state.User.chatDatas,
});

const mapDispatchToProps = (dispatch) => ({
  setCurrentRoomListener: (item) => dispatch(setCurrentRoomListener(item)),
  setCurrentRoomSpeaker: (item) => dispatch(setCurrentRoomSpeaker(item)),
  setCurrentRoom: (item) => dispatch(setCurrentRoom(item)),
  setRoomWidgetLayout: (item) => dispatch(setRoomWidgetLayout(item)),
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
  setCurrentRoomRaisedUsers: (item) =>
    dispatch(setCurrentRoomRaisedUsers(item)),
});

export default connect(mapStateToProps, mapDispatchToProps, null, {
  forwardRef: true,
})(RommWidget);
